<template>
  <div class="order-detail">
    <el-page-header @back="goBack" :title="'订单详情'" />

    <el-card class="detail-card" v-loading="loading">
      <!-- 订单状态 -->
      <div class="status-bar">
        <el-steps :active="getStatusStep(orderInfo.status)" finish-status="success">
          <el-step title="待支付" />
          <el-step title="已支付" />
          <el-step title="已发货" />
          <el-step title="已完成" />
        </el-steps>
      </div>

      <!-- 订单基本信息 -->
      <div class="info-section">
        <h3>订单信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ orderInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(orderInfo.status)">
              {{ orderStatusMap[orderInfo.status] }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ orderInfo.createTime }}</el-descriptions-item>
          <el-descriptions-item label="支付时间">{{ orderInfo.payTime }}</el-descriptions-item>
          <el-descriptions-item label="支付方式">{{ orderInfo.paymentMethod }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ orderInfo.totalAmount }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 收货信息 -->
      <div class="info-section">
        <h3>收货信息</h3>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="收货人">{{ orderInfo.receiverName }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ orderInfo.receiverPhone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址">{{ orderInfo.receiverAddress }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 商品信息 -->
      <div class="info-section">
        <h3>商品信息</h3>
        <el-table :data="orderInfo.items" border style="width: 100%">
          <el-table-column label="商品图片" width="100">
            <template #default="{ row }">
              <el-image
                :src="row.productImage"
                :preview-src-list="[row.productImage]"
                class="product-image"
              />
            </template>
          </el-table-column>
          <el-table-column prop="productName" label="商品名称" min-width="200" />
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">¥{{ row.price }}</template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100" />
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ (row.price * row.quantity).toFixed(2) }}
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 物流信息 -->
      <div class="info-section" v-if="orderInfo.status >= 2">
        <h3>物流信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="快递公司">{{ orderInfo.deliveryCompany }}</el-descriptions-item>
          <el-descriptions-item label="快递单号">{{ orderInfo.deliveryNo }}</el-descriptions-item>
          <el-descriptions-item label="发货时间">{{ orderInfo.shipTime }}</el-descriptions-item>
          <el-descriptions-item label="签收时间">{{ orderInfo.receiveTime }}</el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 退款信息 -->
      <div class="info-section" v-if="orderInfo.status === 5 || orderInfo.status === 6">
        <h3>退款信息</h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="退款金额">¥{{ orderInfo.refundAmount }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ orderInfo.refundApplyTime }}</el-descriptions-item>
          <el-descriptions-item label="退款原因">{{ orderInfo.refundReason }}</el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag :type="orderInfo.status === 6 ? 'success' : 'warning'">
              {{ orderInfo.status === 6 ? '已退款' : '退款中' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮 -->
      <div class="action-bar">
        <el-button
          v-if="orderInfo.status === 1"
          type="primary"
          @click="handleShip"
        >
          发货
        </el-button>
        <el-button
          v-if="orderInfo.status === 5"
          type="warning"
          @click="handleRefund"
        >
          处理退款
        </el-button>
      </div>
    </el-card>

    <!-- 发货对话框 -->
    <el-dialog
      v-model="shipDialogVisible"
      title="订单发货"
      width="500px"
    >
      <el-form
        ref="shipFormRef"
        :model="shipForm"
        :rules="shipRules"
        label-width="100px"
      >
        <el-form-item label="快递公司" prop="deliveryCompany">
          <el-select
            v-model="shipForm.deliveryCompany"
            placeholder="请选择快递公司"
            style="width: 100%"
          >
            <el-option label="顺丰速运" value="SF" />
            <el-option label="中通快递" value="ZTO" />
            <el-option label="圆通速递" value="YTO" />
            <el-option label="韵达快递" value="YD" />
            <el-option label="申通快递" value="STO" />
          </el-select>
        </el-form-item>
        <el-form-item label="快递单号" prop="deliveryNo">
          <el-input v-model="shipForm.deliveryNo" placeholder="请输入快递单号" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="shipDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmShip" :loading="shipSubmitting">
          确认发货
        </el-button>
      </template>
    </el-dialog>

    <!-- 退款处理对话框 -->
    <el-dialog
      v-model="refundDialogVisible"
      title="退款处理"
      width="500px"
    >
      <el-form
        ref="refundFormRef"
        :model="refundForm"
        :rules="refundRules"
        label-width="100px"
      >
        <el-form-item label="退款金额">
          <span>¥{{ orderInfo.refundAmount }}</span>
        </el-form-item>
        <el-form-item label="退款原因">
          <span>{{ orderInfo.refundReason }}</span>
        </el-form-item>
        <el-form-item label="处理结果" prop="status">
          <el-radio-group v-model="refundForm.status">
            <el-radio :label="1">同意退款</el-radio>
            <el-radio :label="0">拒绝退款</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注" prop="remark">
          <el-input
            v-model="refundForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入处理备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="refundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRefund" :loading="refundSubmitting">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getMerchantOrderDetail, shipOrder, auditRefund } from '@/api/order'

const route = useRoute()
const router = useRouter()

// 订单状态映射
const orderStatusMap = {
  0: '待支付',
  1: '已支付',
  2: '已发货',
  3: '已完成',
  4: '已取消',
  5: '退款中',
  6: '已退款'
}

// 获取订单状态对应的标签类型
const getOrderStatusType = (status) => {
  const statusTypeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'success',
    4: 'danger',
    5: 'warning',
    6: 'info'
  }
  return statusTypeMap[status] || 'info'
}

// 获取订单进度步骤
const getStatusStep = (status) => {
  const stepMap = {
    0: 0,
    1: 1,
    2: 2,
    3: 3,
    4: 0,
    5: 1,
    6: 1
  }
  return stepMap[status] || 0
}

// 数据相关
const loading = ref(false)
const orderInfo = ref({
  items: []
})

// 获取订单详情
const getOrderDetail = async () => {
  const orderId = route.params.id
  if (!orderId) {
    ElMessage.error('订单ID不能为空')
    return
  }

  try {
    loading.value = true
    const response = await getMerchantOrderDetail(orderId)
    if (response.code === 200) {
      orderInfo.value = response.data
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败')
  } finally {
    loading.value = false
  }
}

// 返回列表页
const goBack = () => {
  router.push('/merchant/order/list')
}

// 发货相关
const shipDialogVisible = ref(false)
const shipSubmitting = ref(false)
const shipForm = reactive({
  deliveryCompany: '',
  deliveryNo: ''
})

const shipRules = {
  deliveryCompany: [
    { required: true, message: '请选择快递公司', trigger: 'change' }
  ],
  deliveryNo: [
    { required: true, message: '请输入快递单号', trigger: 'blur' }
  ]
}

const handleShip = () => {
  shipDialogVisible.value = true
  shipForm.deliveryCompany = ''
  shipForm.deliveryNo = ''
}

const confirmShip = async () => {
  try {
    shipSubmitting.value = true
    const response = await shipOrder(
      orderInfo.value.id,
      shipForm.deliveryCompany,
      shipForm.deliveryNo
    )
    if (response.code === 200) {
      ElMessage.success('发货成功')
      shipDialogVisible.value = false
      getOrderDetail()
    }
  } catch (error) {
    console.error('发货失败:', error)
    ElMessage.error('发货失败')
  } finally {
    shipSubmitting.value = false
  }
}

// 退款处理相关
const refundDialogVisible = ref(false)
const refundSubmitting = ref(false)
const refundForm = reactive({
  orderId: null,
  status: 1,
  remark: ''
})

const refundRules = {
  status: [
    { required: true, message: '请选择处理结果', trigger: 'change' }
  ],
  remark: [
    { required: true, message: '请输入处理备注', trigger: 'blur' }
  ]
}

const handleRefund = () => {
  refundDialogVisible.value = true
  refundForm.orderId = orderInfo.value.id
  refundForm.status = 1
  refundForm.remark = ''
}

const confirmRefund = async () => {
  try {
    refundSubmitting.value = true
    const response = await auditRefund(refundForm)
    if (response.code === 200) {
      ElMessage.success('处理成功')
      refundDialogVisible.value = false
      getOrderDetail()
    }
  } catch (error) {
    console.error('处理失败:', error)
    ElMessage.error('处理失败')
  } finally {
    refundSubmitting.value = false
  }
}

// 初始化
onMounted(() => {
  getOrderDetail()
})
</script>

<style scoped>
.order-detail {
  padding: 20px;
}

.detail-card {
  margin-top: 20px;
}

.status-bar {
  padding: 20px 0;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.info-section {
  margin-bottom: 30px;
}

.info-section h3 {
  margin-bottom: 20px;
  font-weight: 500;
  color: #303133;
}

.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}

.action-bar {
  margin-top: 30px;
  text-align: center;
}

:deep(.el-descriptions) {
  margin-bottom: 20px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}
</style> 